package com.yitiao.init;

import lombok.SneakyThrows;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class TestWatch {

    String connectString = "101.43.138.173:2181";
    int timeout = 2000;
    ZooKeeper zkClient = null;

    @SneakyThrows
    @Before  // 一个类中最先执行的方法
    public void init() throws IOException {
        System.out.println("before");
        CountDownLatch countDownLatch = new CountDownLatch(1);
        zkClient = new ZooKeeper(connectString, timeout, watchedEvent -> {
            // 收到事件通知后的回调函数（用户的业务逻辑）
            System.out.println(watchedEvent.getType() + "--"
                    + watchedEvent.getState());
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected)
            countDownLatch.countDown();

            // 再次启动监听
//            try {
//                List<String> children = zkClient.getChildren("/",
//                        true);
//                for (String child : children) {
//                    System.out.println(child);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        });
        System.out.println(zkClient.getState());
//        countDownLatch.await();
        System.out.println(zkClient.getState());
    }

    @Test
    public void exist() throws KeeperException, InterruptedException {

//        Stat stat = zkClient.exists("/atguigu", false);
//
//        System.out.println(stat==null? "not exist " : "exist");
    }
}
